import {
  reqGetDepartments,
  reqGetDoctors,
  reqGetHospitalSchedule,
} from "@/api/hospital/hospitalList";
import {
  BookingScheduleList,
  Departments,
  DoctorItem,
} from "@/api/hospital/hospitalList/types";
import { Button, Card, Col, Pagination, Row, Tag, Tree } from "antd";
import Table, { ColumnsType } from "antd/lib/table";
import { DataNode } from "antd/lib/tree";
import React, { useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";

export default function HospitalSchedule() {
  //从地址栏中获取 hoscode 参数
  let { hoscode } = useParams();
  //定义科室列表的状态
  let [departments, setDepartments] = useState<Departments>([]);
  //定义高度状态
  let [height, setHeight] = useState(400);
  //定义展开科室的状态
  let [expandedKeys, setExpandedKeys] = useState<string[]>([]);
  //定义当前科室的状态
  let [depcode, setDepcode] = useState<string>("");
  //定义排班规则的状态
  let [schedules, setSchedules] = useState<BookingScheduleList[]>([]);
  //定义医生的状态
  let [doctors, setDoctors] = useState<DoctorItem[]>([]);
  //定义当前医院名称的状态
  let [hosname, setHosname] = useState<string>("");
  //定义当前医院科室的状态
  let [depname, setDepname] = useState<string>("");
  //定义当前排班日期的状态
  let [workDate, setWorkDate] = useState<string>("");
  //定义分页相关的状态
  let [total, setTotal] = useState<number>(0);
  let [pageSize, setPageSize] = useState<number>(5);
  let [current, setCurrent] = useState<number>(1);
  // 获得 navigate 函数
  let navigate = useNavigate();
  //准备数据
  const treeData: DataNode[] = [
    {
      title: "parent 1",
      key: "0-0",
      children: [
        {
          title: "parent 1-0",
          key: "0-0-0",
          disabled: true,
          children: [
            {
              title: "leaf",
              key: "0-0-0-0",
              disableCheckbox: true,
            },
            {
              title: "leaf",
              key: "0-0-0-1",
            },
          ],
        },
        {
          title: "parent 1-1",
          key: "0-0-1",
          children: [
            {
              title: <span style={{ color: "#1890ff" }}>sss</span>,
              key: "0-0-1-0",
            },
          ],
        },
      ],
    },
  ];
  //医生测试数据
  let data: DoctorItem[] = [
    {
      id: "653520f4c735f1431ec771fc",
      createTime: "2023-07-31 11:47:30",
      updateTime: "2023-07-31 11:47:30",
      isDeleted: 0,
      param: {
        dayOfWeek: "周六",
        depname: "多发性硬化专科门诊",
        hosname: "北京大学国际医院",
      },
      hoscode: "1000_11",
      depcode: "200040878_11",
      title: "医师",
      docname: "",
      skill: "内分泌科常见病。",
      workDate: "2024-01-27",
      workTime: 0,
      reservedNumber: 330,
      availableNumber: 220,
      amount: 100,
      status: 1,
      hosScheduleId: "1685859704024268802",
    },
    {
      id: "653520f4c735f1431ec771fd",
      createTime: "2023-07-31 11:47:30",
      updateTime: "2023-07-31 11:47:30",
      isDeleted: 0,
      param: {
        dayOfWeek: "周六",
        depname: "多发性硬化专科门诊",
        hosname: "北京大学国际医院",
      },
      hoscode: "1000_11",
      depcode: "200040878_11",
      title: "副主任医师",
      docname: "裴育",
      skill: "骨质疏松和骨代谢疾病、糖尿病、甲状腺疾病。",
      workDate: "2024-01-27",
      workTime: 0,
      reservedNumber: 40,
      availableNumber: 39,
      amount: 100,
      status: 1,
      hosScheduleId: "1685859704921849858",
    },
    {
      id: "653520f4c735f1431ec771fe",
      createTime: "2023-07-31 11:47:30",
      updateTime: "2023-07-31 11:47:30",
      isDeleted: 0,
      param: {
        dayOfWeek: "周六",
        depname: "多发性硬化专科门诊",
        hosname: "北京大学国际医院",
      },
      hoscode: "1000_11",
      depcode: "200040878_11",
      title: "副主任医师",
      docname: "邵迎红",
      skill: "内分泌与代谢性疾病。",
      workDate: "2024-01-27",
      workTime: 1,
      reservedNumber: 27,
      availableNumber: 10,
      amount: 100,
      status: 1,
      hosScheduleId: "1685859705790070785",
    },
  ];
  //定义表格结构
  let columns: ColumnsType<DoctorItem> = [
    {
      title: "序号",
      render: (_, record, index) => index + 1,
    },
    {
      title: "职称",
      dataIndex: "title",
    },
    {
      title: "号源时间",
      dataIndex: "workDate",
    },
    {
      title: "总预约数",
      dataIndex: "reservedNumber",
    },
    {
      title: "剩余预约数",
      dataIndex: "availableNumber",
    },
    {
      title: "挂号费(元)",
      dataIndex: "amount",
    },
    {
      title: "擅长技能",
      dataIndex: "skill",
    },
  ];

  //使用 useEffect
  useEffect(() => {
    let getData = async () => {
      //发送请求获取科室的信息
      let departments = await reqGetDepartments(hoscode as string);
      //通过 departments 设置一级科室禁用
      let res = departments.map((item) => {
        return {
          ...item,
          disabled: true,
        };
      });
      //更新科室的状态
      setDepartments(res);
      //获取所有一级科室的 depcode
      let expandedKeys = departments.map((item) => item.depcode);
      //更新展开科室的状态
      setExpandedKeys(expandedKeys);
      //获取第一个一级科室中的第一个二级科室的 depcode
      let depcode = (departments[0].children as Departments)[0].depcode;
      //获取第一个一级科室中的第一个二级科室的 depname
      let depname = (departments[0].children as Departments)[0].depname;
      //更新科室名称的状态
      setDepname(depname);
      //更新当前科室的状态
      setDepcode(depcode);
    };
    getData();
  }, []);

  //计算样式  解决『副作用』
  useEffect(() => {
    //计算高度
    let height =
      document.documentElement.clientHeight - 64 - 34 - 24 - 22 - 14 - 20;
    //更新
    setHeight(height);
    //绑定事件
    window.onresize = function () {
      //计算高度
      let height =
        document.documentElement.clientHeight - 64 - 34 - 24 - 22 - 14 - 20;
      //更新
      setHeight(height);
    };
  }, []);

  //定义 useEffect 回调
  useEffect(() => {
    //判断 depcode
    if (!depcode) return;
    //获取科室的排班以及获取排班的医生信息
    (async () => {
      //发送请求 获取该科室未来的排班
      let schedules = await reqGetHospitalSchedule({
        page: current,
        limit: pageSize,
        hoscode: hoscode as string,
        depcode: depcode,
      });
      //更新排班规则的状态
      setSchedules(schedules.bookingScheduleList);
      //更新医院的名称状态
      setHosname(schedules.baseMap.hosname);
      //更新分页的总数状态
      setTotal(schedules.total);

      //获取第一个排班的日期
      let workDate = schedules.bookingScheduleList[0].workDate;
      //更新workDate 状态
      setWorkDate(workDate);
    })();
  }, [depcode, pageSize, current]);

  //当日期发生变化的时候, 执行
  useEffect(() => {
    //判断
    if(!workDate) return;
    (async () => {
      //请求获取排班的医生信息
      let doctors = await reqGetDoctors({
        hoscode: hoscode as string,
        depcode: depcode,
        workDate: workDate,
      });
      //更新医生状态
      setDoctors(doctors);
    })()
  }, [workDate]);

  return (
    <Card>
      {/* 顶部路径导航 */}
      <p>
        选择：{hosname} / {depname} / {workDate}
      </p>
      {/* 内容区 */}
      <Row gutter={20}>
        {/* 左侧科室 */}
        <Col span={5}>
          <div
            style={{
              border: "solid 1px #ddd",
              height: height,
              overflowY: "auto",
            }}
          >
            <Tree
              expandedKeys={expandedKeys}
              selectedKeys={[depcode]}
              onSelect={async (selectedKeys, info: any) => {
                let depname = info.node.depname;
                let depcode = info.node.depcode;
                //更新选中菜单 keys 的状态
                setDepcode(depcode);
                //更新科室的名称
                setDepname(depname);
              }}
              treeData={departments as []}
              fieldNames={{
                title: "depname",
                key: "depcode",
              }}
            />
          </div>
        </Col>
        {/* 右侧内容 */}
        <Col span={19}>
          {/* 顶部的日期列表 */}
          {schedules.map((item, index) => {
            return (
              <Tag
                color={item.workDate === workDate ? "green" : ""}
                key={index}
                onClick={async () => {
                  //获取
                  let workDate = item.workDate;
                  //更新日期状态
                  setWorkDate(workDate);
                }}
              >
                <div>
                  {item.workDate} {item.dayOfWeek}
                </div>
                <div>
                  {item.availableNumber} / {item.reservedNumber}
                </div>
              </Tag>
            );
          })}
          <div className="h-20"></div>
          {/* 分页结构 */}
          <Pagination
            total={total}
            pageSize={pageSize}
            current={current}
            showSizeChanger={true}
            pageSizeOptions={[5, 10, 15, 20]}
            onChange={(page: number, pageSize: number) => {
              //更新状态
              setCurrent(page);
              setPageSize(pageSize);
            }}
          ></Pagination>
          <div className="h-20"></div>
          {/* 表格结构 */}
          <Table
            columns={columns}
            bordered
            dataSource={doctors}
            rowKey={"id"}
            pagination={false}
          />
          <div className="h-20"></div>
          {/* 返回按钮 */}
          <Button onClick={() => navigate(-1)}>返回</Button>
        </Col>
      </Row>
    </Card>
  );
}
